from django.shortcuts import render
from dwebsocket.decorators import accept_websocket,require_websocket
import json
# Create your views here.

def chess(request):
    return render(request, 'chess/can.html')

def inputinfo(request):
    return render(request, 'chess/inputinfo.html')
        

room_dict = {}

@accept_websocket
def room(request):
    if request.is_websocket():
        for msg in request.websocket:
            msg_content = json.loads(msg)
            
            #有用户加入
            if msg_content['type'] == 'join':
                ## 房间不存在，创建房间，记录第一个用户
                if msg_content['room'] not in room_dict.keys():
                    room_name = msg_content['room']
                    room_dict[room_name] = {msg_content['user']:request.websocket}
                else:
                    ## 房间存在，记录第二个用户
                    room_name = msg_content['room']
                    user_name = msg_content['user']
                    if user_name not in room_dict[room_name].keys():
                        room_dict[room_name][user_name] = request.websocket
            elif msg_content['type'] == 'step':
                ## 下子信息，同步到房间里面的两个人
                for sock in room_dict[room_name].values():
                    sock.send(msg)

    else:
        info = {}
        if request.POST:
            info['room_name'] = request.POST['room_name']
            info['user_name'] = request.POST['user_name']
            info['color'] = request.POST['color']
        return render(request, 'chess/can.html', info)
